import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  // 默认
  // override func application(
  //   _ application: UIApplication,
  //   didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  // ) -> Bool {
  //   GeneratedPluginRegistrant.register(with: self)
  //   return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  // }

  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)

    let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
    let toastChannel = FlutterMethodChannel(name: "com.sainbainu.sainbainu/system_toast",
                                            binaryMessenger: controller.binaryMessenger)
    toastChannel.setMethodCallHandler { (call: FlutterMethodCall, result: @escaping FlutterResult) in
      if call.method == "showToast" {
        if let args = call.arguments as? [String: Any], let message = args["message"] as? String {
          self.showToast(message: message)
          result(nil)
        } else {
          result(FlutterError(code: "INVALID_ARGUMENT", message: "Message is required", details: nil))
        }
      } else {
        result(FlutterMethodNotImplemented)
      }
    }

    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  private func showToast(message: String) {
    let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)

    DispatchQueue.main.async {
        if let topViewController = self.getTopViewController() {
            topViewController.present(alert, animated: true)

            // 2 秒后自动关闭
            DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                alert.dismiss(animated: true, completion: nil)
            }
        }
    }
  }

  // 获取当前的顶层视图控制器
  private func getTopViewController() -> UIViewController? {
      guard var topController = self.window?.rootViewController else { return nil }
      while let presentedViewController = topController.presentedViewController {
          topController = presentedViewController
      }
      return topController
  }
}
